package groep3.ssc.coachViews;

import groep3.ssc.controllers.ModelRepository;
import groep3.ssc.helpers.DataFunctions;
import groep3.ssc.main.R;
import groep3.ssc.model.Scheme;
import groep3.ssc.model.SchemeEntry;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class SchemeManager extends Activity
{
    //private DbController db;
    private Spinner sp;
    private Button saveButton;
    protected ArrayAdapter<Scheme> adapter;
    protected Scheme loadedScheme = null;
    protected ModelRepository modelRepository;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        modelRepository = ModelRepository.getInstance();

        setContentView(R.layout.scheme_manager);

        initializeSpinner();

        saveButton = (Button) findViewById(R.id.btnSaveScheme);

        saveButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                EditText etSchemeName = (EditText) findViewById(R.id.etSchemeName);
                EditText etSchemeAbbr = (EditText) findViewById(R.id.etSchemeAbbreviation);
                String schemeName = etSchemeName.getText().toString();
                String schemeAbbreviation = etSchemeAbbr.getText().toString();

                if (schemeName.equals("") || schemeAbbreviation.equals(""))
                {
                    Resources res = getResources();
                    CharSequence text = res.getString(R.string.errorNameOrAbbreviationEmpty);
                    int duration = Toast.LENGTH_SHORT;

                    Toast toast = Toast.makeText(SchemeManager.this, text, duration);
                    toast.show();
                } else
                {

                    if (loadedScheme == null)
                    {
                        Scheme schemeToSave = new Scheme(schemeName, schemeAbbreviation);
                        modelRepository.addScheme(schemeToSave);
                        adapter.add(schemeToSave);
                        sp.setSelection(adapter.getPosition(schemeToSave), true);
                        displayScheme(schemeToSave);
                    } else
                    {
                        loadedScheme.setTitle(schemeName);
                        loadedScheme.setAbbreviation(schemeAbbreviation);
                        modelRepository.updateScheme(loadedScheme);
                        adapter.notifyDataSetChanged();
                    }
                    SkateViewManagerActivity.adapter.notifyDataSetChanged();
                }

            }
        });
    }

    private void initializeSpinner()
    {
        Resources res = getResources();
        String schemeManagerNew = res.getString(R.string.txtSchemeManagerNew);
        String schemeManagerNewAbbr = res.getString(R.string.txtSchemeManagerNewAbbr);
        
        adapter = new ArrayAdapter<Scheme>(this, android.R.layout.simple_spinner_item);
        adapter.add(new Scheme(schemeManagerNew, schemeManagerNewAbbr));
        adapter.addAll(modelRepository.getListOfSchemes());
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_1);

        sp = (Spinner) findViewById(R.id.spSelectedScheme);
        sp.setAdapter(adapter);
        sp.setMinimumHeight(50);
        sp.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                Scheme selectedScheme = adapter.getItem(position);
                displayScheme(selectedScheme);
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0)
            {

            }
        });
    }

    protected void displayScheme(Scheme scheme)
    {
        EditText etSchemeName = (EditText) findViewById(R.id.etSchemeName);
        EditText etSchemeAbbr = (EditText) findViewById(R.id.etSchemeAbbreviation);

        if (scheme.getId() == 0)
        {
            etSchemeName.setText("");
            etSchemeAbbr.setText("");

            TableLayout table = (TableLayout) findViewById(R.id.tblSchemeData);
            final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(table.getWindowToken(), 0);//hide keyboard

            table.removeAllViews();
            this.loadedScheme = null;
        } else
        {
            etSchemeName.setText(scheme.getTitle());
            etSchemeAbbr.setText(scheme.getAbbreviation());

            TableLayout table = (TableLayout) findViewById(R.id.tblSchemeData);
            //TableRow th = (TableRow) findViewById(R.id.tblSchemeHeaderRow);

            LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

            int rows = table.getChildCount();

            table.addView(createSchemeTableHeaderRow(layout));

            scheme.setEntries(modelRepository.getScheme(scheme.getId()).getEntries());

            for (SchemeEntry entry : scheme.getEntries())
            {
                TableRow newRow = createRowFromSchemeEntry(scheme, entry, layout);
                table.addView(newRow, layout);
            }

            TableRow v = createNewSchemeEntryInputRow(scheme, layout);
            table.addView(v);
            v.getChildAt(1).requestFocus();

            this.loadedScheme = scheme;

            for (int i = 0; i < rows; i++)
            {
                table.removeViewAt(0);
            }
        }

    }

    private TableRow createSchemeTableHeaderRow(LayoutParams layout)
    {
        TableRow headerRow = new TableRow(this);

        headerRow.setLayoutParams(layout);

        TextView h1 = new TextView(this);
        TextView h2 = new TextView(this);
        TextView h3 = new TextView(this);

        h1.setText(R.string.txtRoundNumber);
        h2.setText(R.string.txtLapTime);
        h3.setText(R.string.txtTotalTime);

        h1.setTextSize(20);
        h2.setTextSize(20);
        h3.setTextSize(20);

        h1.setWidth(dip(this, 200));
        h2.setWidth(dip(this, 500));
        h3.setWidth(dip(this, 300));

        headerRow.addView(h1);
        headerRow.addView(h2);
        headerRow.addView(h3);

        return headerRow;
    }

    private int dip(Context context, int pixels)
    {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pixels * scale + 0.5f);
    }

    private TableRow createRowFromSchemeEntry(Scheme scheme, SchemeEntry entry, LayoutParams layout)
    {
        TextView tvRoundNumber = new TextView(this);
        tvRoundNumber.setText(String.valueOf(entry.getLapNumber()));
        tvRoundNumber.setTextSize(20);

        EditText etLapTime = new EditText(this);
        etLapTime.setText(DataFunctions.longToFormattedTime(entry.getLapTime()));
        etLapTime.setTextSize(20);
        etLapTime.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        etLapTime.setOnEditorActionListener(new EditTextViewListener(scheme, entry));

        TextView tvTotalTime = new TextView(this);
        tvTotalTime.setText(DataFunctions.longToFormattedTime((int) entry.getTotalTime()));
        tvTotalTime.setTextSize(20);

        tvRoundNumber.setLayoutParams(layout);
        etLapTime.setLayoutParams(layout);
        tvTotalTime.setLayoutParams(layout);

        TableRow row = new TableRow(this);
        row.setLayoutParams(layout);

        row.addView(tvRoundNumber);
        row.addView(etLapTime);
        row.addView(tvTotalTime);
        row.setMinimumHeight(50);
        row.setGravity(Gravity.CENTER_VERTICAL);

        return row;
    }

    private TableRow createNewSchemeEntryInputRow(Scheme scheme, LayoutParams layout)
    {
        TextView tvRoundNumber = new TextView(this);
        tvRoundNumber.setText(String.valueOf(scheme.getEntries().size() + 1));
        tvRoundNumber.setTextSize(20);

        EditText etLapTime = new EditText(this);
        etLapTime.setTextSize(20);
        etLapTime.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        etLapTime.setOnEditorActionListener(new EditTextViewListener(scheme));

        tvRoundNumber.setLayoutParams(layout);
        etLapTime.setLayoutParams(layout);

        TableRow row = new TableRow(this);
        row.setLayoutParams(layout);

        row.addView(tvRoundNumber);
        row.addView(etLapTime);
        row.setMinimumHeight(50);
        row.setGravity(Gravity.CENTER_VERTICAL);
        return row;
    }

    private class EditTextViewListener implements OnEditorActionListener
    {

        private Scheme scheme;
        private SchemeEntry entry;

        public EditTextViewListener(Scheme sc, SchemeEntry entry)
        {
            this.scheme = sc;
            this.entry = entry;
        }

        public EditTextViewListener(Scheme sc)
        {
            this(sc, null);
        }

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            String newValue = String.valueOf(v.getText());
            if (!newValue.equals(""))
            {
                if (entry == null)
                {
                    entry = new SchemeEntry(scheme.getEntries().size() + 1, (int) DataFunctions.FormattedTimeToInt(newValue));
                    scheme.addEntry(entry);
                } else
                {
                    entry.setLapTime((int) DataFunctions.FormattedTimeToInt(newValue));
                }
                modelRepository.updateScheme(scheme);
            }

            displayScheme(scheme);
            return true;
        }
    }
}
